package com.example.jwt.framework.security.handle;

import com.example.jwt.framework.security.core.PermissionService;
import com.example.jwt.framework.security.core.TokenManager;
import com.example.jwt.framework.security.model.LoginUser;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.function.Supplier;

/**
 * 动态权限处理器，如果设置了动态权限，PermissionService权限校验注解应该可以去掉了。
 * @see PermissionService
 * @author LiJY
 * @date 2024/12/05
 */
@Component
public class DynamicAuthorizationManager implements AuthorizationManager<RequestAuthorizationContext> {

    private final TokenManager tokenManager;

    public DynamicAuthorizationManager(TokenManager tokenManager) {
        this.tokenManager = tokenManager;
    }

    /**
     * 动态权限检验处理逻辑,方法标记位过时，
     *
     * @param authentication 身份验证
     * @param object         对象
     * @return {@link AuthorizationDecision }
     */
    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext object) {
        // 获取访问url
        String requestURI = object.getRequest().getRequestURI();
        LoginUser loginUser = tokenManager.getLoginUser(object.getRequest());

        // 模拟从数据库或者缓存里面查询拥有当前URI的权限的角色
        String[] allRole = new String[]{"admin","user"};
        // 获取当前用户权限
        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
        // 判断是否拥有权限
        for (String role : allRole) {
            for (GrantedAuthority r : authorities) {
                if (role.equals(r.getAuthority())) {
                    return new AuthorizationDecision(true);
                }
            }
        }
        return new AuthorizationDecision(false);
    }
}
